/**
 * 数据管理=>瞬时数据查询
 */
import * as React from "react";
import { Modal, Spin } from "antd";
import DTTable from "./compontents/DTTable";
import DtPowerCondition, {
  DtPowerDevice,
  DtPowerParam,
} from "./compontents/Condition";
import DtPowerCharts, { DtPowerData } from "./compontents/TabCharts";
import { getNetWorkData } from "../../../../utils/common";
import {
  getDeviceDtUrl,
  getDeviceLatestDataUrl,
} from "./compontents/serverApi";

import "./index.less";

export interface dtPowerProps {}

export interface dtPowerState {}

class dtPower extends React.Component<dtPowerProps, dtPowerState> {
  private dtDevice: DtPowerDevice = {
    deviceId: null,
    no: null,
    name: null,
    devAddr: null,
  };
  //设备最新瞬时量数据
  private lastData: any = null;
  //瞬时量集合数据
  private dtPowerData: DtPowerData = {
    voltage: [], //电压
    current: [], //电流
    powerFactory: [], //功率因数
    activePower: [], //有功功率
    reactivePower: [], //无功功率
  };
  state = { loading: false };

  render() {
    return (
      <div className="dtPower">
        <div className="bare_body" style={{ marginBottom: 12 }}>
          <DtPowerCondition
            chooseDevice={(device) => {
              this.chooseDevice(device);
            }}
            query={(param) => {
              this.query(param);
            }}
          />
          <DTTable device={this.dtDevice} lastData={this.lastData} />
        </div>
        <Spin spinning={this.state.loading}>
          <DtPowerCharts data={this.dtPowerData} />
        </Spin>
      </div>
    );
  }

  //选择设备
  chooseDevice(device: DtPowerDevice) {
    this.dtDevice = device;
    getNetWorkData(
      getDeviceLatestDataUrl,
      { deviceId: device.deviceId },
      this,
      (result) => {
        if (result.success) {
          this.lastData = result.data;
        } else {
          this.lastData = null;
        }
        this.forceUpdate();
      },
      (err) => {
        Modal.error({
          title: "系统出错，请稍后再试！",
        });
      }
    );
  }

  //查询
  query(param: DtPowerParam) {
    this.setState({ loading: true });
    getNetWorkData(
      getDeviceDtUrl,
      param,
      this,
      (result) => {
        this.setState({ loading: false });
        if (result.success) {
          this.dtPowerData = {
            voltage: result.data.VOLTAGE, //电压
            current: result.data.CURRENT, //电流
            powerFactory: result.data.POWER_FACTOR, //功率因数
            activePower: result.data.ACTIVE_POWER, //有功功率
            reactivePower: result.data.REACTIVE_POWER, //无功功率
          };
          this.forceUpdate();
        }
      },
      (err) => {
        this.setState({ loading: false });
        Modal.error({
          title: "系统出错，请稍后再试！",
        });
      }
    );
  }
}

export default dtPower;
